package com.eltsistemas.dao;

import java.sql.Date;
import java.util.Calendar;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.eltsistemas.modelo.Afastamento;

public class AfastamentoDao {
	
	private Session session;
	
	public AfastamentoDao(Session session)
	{
		this.session=session;
	}
	
	public Long verificaPeriodo(Calendar dtInicio, Calendar dtFim, Long id_Funcionario)
	{
		Date dtInicial = new Date(dtInicio.getTimeInMillis());
		Date dtFinal = new Date(dtFim.getTimeInMillis());
		
		Query query = session.createQuery("SELECT MAX(a.id) from Afastamento as a where ((a.dataInicio between '"+dtInicial+"' and '"+dtFinal+"') or (a.dataFim between '"+dtInicial+"' and '"+dtFinal+"')) and id_funcionario=:id_Funcionario" );
		query.setLong("id_Funcionario", id_Funcionario);
		
		return (Long) query.uniqueResult();
	}
	
	public List<Afastamento> verificaPeriodo_ForUpdate(Calendar dtInicio, Calendar dtFim, Long id_Afastamento, Long id_Funcionario)
	{
		Date dtInicial = new Date(dtInicio.getTimeInMillis());
		Date dtFinal = new Date(dtFim.getTimeInMillis());
		
		Query query = session.createQuery("from Afastamento as a where ((a.dataInicio between '"+dtInicial+"' and '"+dtFinal+"') or (a.dataFim between '"+dtInicial+"' and '"+dtFinal+"')) and id != :id_Afastamento and id_funcionario=:id_Funcionario");
		query.setLong("id_Afastamento", id_Afastamento);
		query.setLong("id_Funcionario", id_Funcionario);
		
		return query.list();
	}

	public Long verificaVigente(Long id_Funcionario)
	{
		Query query = session.createQuery("SELECT MAX(a.id) from Afastamento as a where id_funcionario=:id_Funcionario and vigente=:vigente" );
		query.setLong("id_Funcionario", id_Funcionario);
		query.setBoolean("vigente", true);
		return (Long) query.uniqueResult();
	}
}
